package com.ruoyi.system.xcenter.backup;

import cn.hutool.extra.mail.MailUtil;
import com.ruoyi.common.utils.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.SqlSessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
class DBUtils {

    private static final String PREFIX_LOG = "【自定义DB工具】";

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    public boolean excuteQuerySql(String sql){
        log.info(PREFIX_LOG+"执行查询sql:"+sql);
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        PreparedStatement pst = null;
        SqlSession session = getSqlSession();
//        ResultSet result = null;
        try {
            pst = session.getConnection().prepareStatement(sql);
            return pst.execute();
//            ResultSetMetaData md = result.getMetaData(); //获得结果集结构信息,元数据
//            int columnCount = md.getColumnCount();   //获得列数
//            while (result.next()) {
//                Map<String,Object> rowData = new HashMap<String,Object>();
//                for (int i = 1; i <= columnCount; i++) {
//                    rowData.put(md.getColumnName(i), result.getObject(i));
//                }
//                list.add(rowData);
//            }
        } catch (SQLException e) {
            e.printStackTrace();
            String mail = MailUtil.send("941212702@qq.com", "日志数据备份", "数据库备份异常," + ExceptionUtil.getExceptionMessage(e), true);
            log.info("邮件已发送.{}", mail);
        }finally {
            if(pst!=null){
                try {
                    pst.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            closeSqlSession(session);
        }
        return false;
    }

    /**
     * 获取sqlSession
     * @return
     */
    public SqlSession getSqlSession(){
        return SqlSessionUtils.getSqlSession(sqlSessionTemplate.getSqlSessionFactory(),
                sqlSessionTemplate.getExecutorType(), sqlSessionTemplate.getPersistenceExceptionTranslator());
    }

    /**
     * 关闭sqlSession
     * @param session
     */
    public void closeSqlSession(SqlSession session){
        SqlSessionUtils.closeSqlSession(session, sqlSessionTemplate.getSqlSessionFactory());
    }
}